import javax.activation.MimeType;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/DownloadServlet1")
public class DownloadServlet1 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         //获取请求参数,文件名
        String filename=req.getParameter("filename");
        //1.使用字节流加载文件进内存
        //1.1找到服务器路径
        ServletContext servletContext=this.getServletContext();
        String realPath = servletContext.getRealPath("/img/"+filename);
        //1.2用字节流关联
        ServletInputStream fis=req.getInputStream();

        //2.设置response响应头
        //2.1设置响应头:content-type= ;
        String mimeType = servletContext.getMimeType(filename);
        resp.setHeader("content-type",mimeType);
        //2.2设置响应头打开方式:content-disposition
        resp.setHeader("content-disposition","attachment;filename="+filename);
        //将输入流的数据写到输出流
        ServletOutputStream sos=resp.getOutputStream();
        byte [] buff=new byte[1024*8];
        int len=0;
        while ((len=fis.read(buff))!=-1){
            sos.write(buff,0,len);
        }
        fis.close();
    }
}